<?php

namespace app\service;

use support\Log;

class Logger
{

  private static function mergeBackTrace(string &$msg, int $level = 3): void
  {
    // 获取调用者信息
    $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
    $callerInfo = [];
    foreach ($backtrace as $index => $frame) {
      // 只显示3层
      if ($index >= $level) {
        break;
      } else {
        $callerInfo[] = sprintf(
          "File %d: %s:%d %s()",
          $index,
          basename($frame['file']),
          $frame['line'],
          $frame['function'] ?? 'main'
        );
      }
    }
    $callerInfo = implode(" -> ", $callerInfo);
    $msg = sprintf("%s=>%s", $msg, $callerInfo);
  }

  public static function log($msg, array $context = [], int $level = 0): void
  {
    if ($level > 0) self::mergeBackTrace($msg, $level);
    Log::info($msg, $context);
  }

  public static function error($msg, array $context = [], int $level = 3): void
  {
    if ($level > 0) self::mergeBackTrace($msg, $level);
    Log::error($msg, $context);
  }

  public static function debug($msg, array $context = [], int $level = 3): void
  {
    if ($level > 0) self::mergeBackTrace($msg, $level);
    Log::debug($msg, $context);
  }

  public static function critical($msg, array $context = [], int $level = 3): void
  {
    if ($level > 0) self::mergeBackTrace($msg, $level);
    Log::critical($msg, $context);
  }
}
